package com.zone.gateway.core.socket.agreement.impl;

import com.zone.gateway.core.socket.agreement.IRequestParser;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.multipart.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: zongzi
 * @description: content-type = form-data的post请求解析器
 * @date: 2025/4/22
 */
public class PostFormDataParser implements IRequestParser {

    private final Logger logger = LoggerFactory.getLogger(PostFormDataParser.class);

    @Override
    public Map<String, Object> analysis(FullHttpRequest httpRequest) {
        Map<String, Object> dataMap = new HashMap<>();

        // 1. 获取Content-Type
        String contentType = httpRequest.headers().get(HttpHeaderNames.CONTENT_TYPE);

        // 2. 获取boundary
        String[] contentTypeArray = contentType.split(";");
        String boundary = null;
        for (String item : contentTypeArray) {
            if (item.trim().startsWith("boundary=")) {
                boundary = item.substring(item.indexOf('=') + 1);
                break;
            }
        }
        if (boundary == null) {
            throw new RuntimeException("No boundary found in multipart/form-data request");
        }

        try {
            // 3. 创建HTTP解析工厂
            HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);

            // 4. 创建HTTP POST请求解码器
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(factory, httpRequest);

            // 5. 遍历所有HTTP数据部分
            while (decoder.hasNext()) {
                InterfaceHttpData data = decoder.next();
                if (data != null) {
                    try {
                        processHttpData(data, dataMap);
                    } finally {
                        // 释放资源
                        data.release();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Error parsing form-data", e);
            throw new RuntimeException("Error parsing form-data");
        }
        return dataMap;
    }

    /**
     * 处理HTTP数据
     */
    private void processHttpData(InterfaceHttpData data, Map<String, Object> dataMap) {
        try {
            switch (data.getHttpDataType()) {
                case Attribute:
                    // 处理普通表单字段
                    Attribute attribute = (Attribute) data;
                    dataMap.put(attribute.getName(), attribute.getValue());
                    break;
                case FileUpload:
                    // 处理文件上传
                    FileUpload fileUpload = (FileUpload) data;
                    if (fileUpload.isCompleted()) {
                        // 创建文件上传信息对象
                        FileInfo fileInfo = new FileInfo();
                        fileInfo.setFileName(fileUpload.getFilename());
                        fileInfo.setContentType(fileUpload.getContentType());
                        fileInfo.setSize(fileUpload.length());
                        fileInfo.setContent(fileUpload.get());
                        dataMap.put(fileUpload.getName(), fileInfo);
                    }
                    break;
                default:
                    logger.warn("Unsupported HTTP data type: {}", data.getHttpDataType());
            }
        } catch (IOException e) {
            logger.error("Error processing HTTP data", e);
            throw new RuntimeException("Error processing HTTP data: " + data.getName());
        }
    }
}
